package com.xmy.service.impl;

import com.xmy.dao.BaseDao;
import com.xmy.entity.Book;
import com.xmy.service.BookService;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookServiceImpl extends BaseDao implements BookService {
    @Override
    public List<Book> SelAllBook(int page, int size) {
        String sql = "select * from ebook_entry limit ?,?";
        Object[] objects = {(page-1)*size,size};
        List<Book> books = new ArrayList<Book>();
        try{
            ResultSet rs = executeQuery(sql,objects);
            while (rs.next()){
                Book book = new Book();
                book.setId(rs.getInt(1));
                book.setTypeId(rs.getInt(2));
                book.setTitle(rs.getString(3));
                book.setSummary(rs.getString(4));
                book.setUploaduser(rs.getString(5));
                book.setCreatedate(rs.getDate(6));
                books.add(book);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return books;
    }

    @Override
    public int addBook(Book book) {
        String sql = "INSERT INTO `ebookdb`.`ebook_entry` (`id`, `categoryId`, `title`, `summary`, `uploaduser`, `createdate`) VALUES (null, ?, ?, ?, ?, ?)";
        Object [] objects = {book.getTypeId(),book.getTitle(),book.getSummary(),book.getUploaduser(),book.getCreatedate()};
        return executeUpdate(sql,objects);
    }

    @Override
    public int updateBook(Book book,int id) {
        String sql = "UPDATE `ebookdb`.`ebook_entry` SET `categoryId`=?, `title`=?, `summary`=?, `uploaduser`=?, `createdate`=? WHERE (`id`=?)";
        Object[] objects = {book.getTypeId(),book.getTitle(),book.getSummary(),book.getUploaduser(),book.getCreatedate(),id};
        return executeUpdate(sql,objects);
    }

    @Override
    public int delBook(int id) {
        String sql = "delete from ebook_entry where id = ?";
        Object [] objects = {id};
        return executeUpdate(sql,objects);
    }

    @Override
    public int selCount() {
        String sql = "select count(1) from ebook_entry";
        int count = 0;
        try{
            ResultSet rs = executeQuery(sql,null);
            rs.next();
            count = rs.getInt(1);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }
}
